package com.lzx.adx.report.support.strategy.v3.media;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayDataDataserviceAdConversionUploadModel;
import com.alipay.api.domain.ConversionData;
import com.alipay.api.request.AlipayDataDataserviceAdConversionUploadRequest;
import com.alipay.api.response.AlipayDataDataserviceAdConversionUploadResponse;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.CallTypeMappingDTO;
import com.lzx.adx.report.dto.OcpxAccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.dto.zfb.UuidTypeDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
@MediaType(MediaChannelConstant.ZFB)
public class ZfbChannel extends AbstractChannel{

    @Override
    public ResponseEntity callback(ReportDTO reportDTO, OcpxAccountDTO accountDTO, String callType, String ts) {
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if (!base) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        Map<String, CallTypeMappingDTO> callTypeMap = getCallTypeMap(accountDTO);
        CallTypeMappingDTO callTypeMappingDTO = callTypeMap.get(callType);
        String eventType = callTypeMappingDTO.getMediaReturnType();

        try{
        //获取配置信息
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setAppId(accountDTO.getAppId());
        alipayConfig.setPrivateKey(accountDTO.getPrivateKey());
        alipayConfig.setAlipayPublicKey(accountDTO.getPublicKey());
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);

        // 构造请求参数以调用接口
        AlipayDataDataserviceAdConversionUploadRequest request = new AlipayDataDataserviceAdConversionUploadRequest();
        AlipayDataDataserviceAdConversionUploadModel model = new AlipayDataDataserviceAdConversionUploadModel();


        UuidTypeDTO uuidType = handerUUIdType(reportDTO);

        // 设置业务令牌
        model.setBizToken(accountDTO.getMediaKey());

        // 设置转化明细数据
        List<ConversionData> conversionDataList = new ArrayList<ConversionData>();
        ConversionData conversionDataList0 = new ConversionData();
        conversionDataList0.setSource("CALLBACK");
        conversionDataList0.setBizNo(reportDTO.getBizRequestId());
        conversionDataList0.setConversionType(eventType);
        conversionDataList0.setConversionTime(System.currentTimeMillis() / 1000);
        conversionDataList0.setUuidType(uuidType.getType());
        conversionDataList0.setUuid(uuidType.getValue());
        conversionDataList0.setCallbackExtInfo(reportDTO.getCallback());
        conversionDataList.add(conversionDataList0);
        model.setConversionDataList(conversionDataList);


        request.setBizModel(model);

        log.info("账号id{},请求id{} 给支付宝上报的参数为：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), JSON.toJSON(request));
        AlipayDataDataserviceAdConversionUploadResponse response = alipayClient.execute(request);
        log.info("账号id{},请求id{}  给支付宝上报响应的结果为：{}",reportDTO.getDspId(), reportDTO.getBizRequestId(),JSON.toJSON(response));
        }catch(Exception e){
            log.error("给支付宝上报出现了异常， 异常的错误为{}",e);
        }
        return ResponseEntity.ok(new Result());
    }


    private UuidTypeDTO handerUUIdType(ReportDTO reportDTO) {
        if(StringUtils.isNotBlank(reportDTO.getOaidSum()) && !reportDTO.getOaidSum().equals("__OAID_MD5__")){
            return new UuidTypeDTO("OAID_MD5",reportDTO.getOaidSum());
        }
        if(StringUtils.isNotBlank(reportDTO.getIdfaSum()) && !reportDTO.getIdfaSum().equals("__IDFA_MD5__")){
            return new UuidTypeDTO("IDFA_MD5",reportDTO.getIdfaSum());
        }
        log.info("设备信息什么都没有取到，给随机值 {} {}",reportDTO.getDspId(),reportDTO.getRequestId());
        return new UuidTypeDTO("OAID_MD5", IdUtil.fastSimpleUUID());
    }
}
